<template>
  <el-drawer
    v-model="isVisible"
    :title="title"
    :size="width"
    :direction="direction"
    :before-close="onClose"
    :destroy-on-close="destroyOnClose"
    :close-on-click-modal="closeOnClickModal"
    :close-on-press-escape="closeOnPressEscape"
    class="side-drawer"
  >
    <div class="drawer-content">
      <slot></slot>
    </div>
    <template #footer v-if="$slots.footer || showDefaultFooter">
      <div class="drawer-footer">
        <slot name="footer">
          <el-button @click="onClose">取消</el-button>
          <el-button type="primary" @click="onConfirm">确定</el-button>
        </slot>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '侧边表单',
  },
  width: {
    type: String,
    default: '30%',
  },
  direction: {
    type: String,
    default: 'rtl', // 从右侧弹出
    validator: (val) => ['ltr', 'rtl', 'ttb', 'btt'].includes(val),
  },
  destroyOnClose: {
    type: Boolean,
    default: false,
  },
  closeOnClickModal: {
    type: Boolean,
    default: true,
  },
  closeOnPressEscape: {
    type: Boolean,
    default: true,
  },
  showDefaultFooter: {
    type: Boolean,
    default: true,
  },
})

const emit = defineEmits(['update:visible', 'close', 'confirm'])

const isVisible = ref(props.visible)

// 监听visible属性变化
watch(
  () => props.visible,
  (val) => {
    isVisible.value = val
  }
)

// 监听内部visible状态变化，通知父组件
watch(isVisible, (val) => {
  emit('update:visible', val)
})

const onClose = () => {
  isVisible.value = false
  emit('close')
}

const onConfirm = () => {
  emit('confirm')
  isVisible.value = false
}
</script>

<style lang="scss" scoped>
.side-drawer {
  .drawer-content {
    padding: 10px;
  }

  .drawer-footer {
    display: flex;
    justify-content: flex-end;
    padding: 10px 20px;
    border-top: 1px solid #e4e7ed;

    .el-button {
      margin-left: 10px;
    }
  }
}

// 抽屉弹出动画
:deep(.el-drawer__body) {
  padding: 0;
  overflow-y: auto;
}

:deep(.el-drawer) {
  overflow: visible;

  .el-drawer__header {
    margin-bottom: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #e4e7ed;

    .el-drawer__title {
      font-size: 16px;
      font-weight: 600;
    }
  }
}
</style>
